﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OutdoorLib.BaseEntity.Infrastructure;
using Grishko.Tools;
using Grishko.DataTier.SqlSentence;

public partial class Ctl_ctlFilterPanel : System.Web.UI.UserControl
{
    string qListType = "ListTagName";
    string qID = "ID";

    private Filter __Filter = null;
    
    public Func<bool> OnPopulate = null;

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        //ctlFilterEditor1.GetWhere = GetListWhere;
        //ctlFilterEditor1.OnImChange = ctlFilterEditor1_OnImChange;

        //ctlFilterEditor1.SaveMethod = Save;

        //OnOff_List.Attributes.Add("onClick", "OnOff_List();");

    }
    private bool ctlFilterEditor1_OnImChange ()
    {
        btnFind_Click(null, null);
        return true;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            MyBind();
        //Onclick на лекскему        
        TxtLexema.Attributes.Add("onKeyPress", string.Format("OnEnterClick('{0}',event);", TxtLexema.ClientID));

        if (Request["__EVENTTARGET"] == TxtLexema.ClientID)
        {
            btnFind_Click(null, null);
        }
    }


    protected ScriptEngine GetListWhere()
    {
        if (null == _Filter)
                        return null;

        return _Filter.Where;
    }

    private void MyBind()
    {
        #region Заполнить cmbFilterlist
        Func<List<Filter>, bool> f = delegate(List<Filter> l)
        {

            cmbFilterlist.Items.Clear();
            foreach (Filter j in l)
            {
                ListItem itm = new ListItem();
                itm.Text = j.Caption;
                itm.Value = j.ID;
                itm.Selected = (j.ID == CurrentId);
                cmbFilterlist.Items.Add(itm);
            }

            return true;
        };


        if (null == _Filter)
                        return;

        List<Filter> fList = AppEnvironment.FilterSource.GetFilters(_Filter.TagName);
        f(fList);
        #endregion

        //MyListControl1.DataSource = _Filter;
        DataBind();
    }
    /// <summary>
    /// Добавить фильтр
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        string sListType = AppEnvironment.FilterSource.GetNewRecordParam_Filter(null==_Filter?CurrentListType:_Filter.TagName);
        string[] arr = {GlobalConstants .qPrefNEW_RECORD +  Guid .NewGuid ().ToString (), sListType };        
        string s = string.Format("FilterEditor.aspx?ID={0}&TagName={1}", arr);
        AppEnvironment.PageNavigator.Redirect(AppEnvironment.PageNavigator.AddReturnUrlParam(s));

    }

    /// <summary>
    /// Id текущего фильтра
    /// </summary>
    public string CurrentId
    {
        get
        {
            return Request.QueryString[qID];
        }
    }

    /// <summary>
    /// Если фильтр опреелен - вынимаем категорию из него если нет ищем в командной строке
    /// </summary>
    protected string CurrentListType
    {
        get
        {
            //if (__Filter != null)
            //    return __Filter.ListType.ToString ();

            return Request.QueryString[qListType];
        }
    }


    // Если - четко задан фильтр - беретпо ID
    // Если id - нет - но указанна категория - берет первый из списка относящихся к категории и вызывает редирект - по ид
    public Filter _Filter
    {
        get
        {
            if (null != __Filter)
                return __Filter;

            //если указан ид фильтра
            if (!string.IsNullOrEmpty(CurrentId))
            {
                __Filter = AppEnvironment.FilterSource.Get(CurrentId);
                return __Filter;
            }


            //если указан тип  фильтров
            if (!string.IsNullOrEmpty(CurrentListType))
            {
                List<Filter> fSet = AppEnvironment.FilterSource.GetFilters(CurrentListType);
                
                if (fSet.Count ==0)
                            return null;

                __Filter = fSet[0];
                return __Filter;
            }

            return null;
        }

    }

    /// <summary>
    /// Проверяет существование фильтра с указанным ID
    /// </summary>
    /// <returns></returns>
    public bool IsExistst(string FilterID)
    {
        return (null != AppEnvironment.FilterSource.Get(FilterID));

    }

    /// <summary>
    /// Взять новый фильтр и редиректнуться с ним
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cmbFilterlist_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList cmb = (DropDownList)sender;
        string id = cmb.SelectedItem.Value;
        QueryStringTools.RefreshPage(string.Format("ID={0}", id));

    }
    
    protected void btnEdit_Click(object sender, ImageClickEventArgs e)
    {

        string id = cmbFilterlist.SelectedItem.Value;
        //QueryStringTools.RefreshPage("FilterEditor.aspx", string.Format("ID={0}", id));
        string s = string.Format("FilterEditor.aspx?ID={0}", id);
        AppEnvironment.PageNavigator.Redirect(AppEnvironment.PageNavigator.AddReturnUrlParam(s));
    }
    
    protected void btnFind_Click(object sender, ImageClickEventArgs e)
    {
        _Filter.Where.Lexeme = TxtLexema.Text;
        
        if (null != OnPopulate)
                        OnPopulate();

        MyBind();

    }

    protected void btnDel_Click(object sender, ImageClickEventArgs e)
    {
        string s = _Filter.TagName;
        AppEnvironment.FilterSource.Delete(_Filter);
        QueryStringTools.RefreshPageWitchNewParams(string.Format("ListTagName={0}", s));
    }
    
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        string sUrl = AppEnvironment.PageNavigator.GetNewObjectUrlCommand(_Filter.ObjectPageKey,
                                                                        _Filter.Where.EntityTypeTagName,
                                                                        _Filter.AddUrlHandler_Insert);
        AppEnvironment.PageNavigator.Redirect(sUrl);

    }

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        if (MultiView1.ActiveViewIndex == -1)
            MultiView1.ActiveViewIndex = 0;
        else
            MultiView1.ActiveViewIndex = -1;

    }
}
